package com.flaremars.picker.utils.http.newhttp;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * Created by FlareMars on 2016/1/28.
 */
public abstract class ProgressListener {
    private static final int REQUEST_UPDATE = 0x01;

    private static class UIHandler extends Handler {
        private final WeakReference<ProgressListener> progressRequestListenerWeakReference;

        public UIHandler(Looper looper, ProgressListener listener) {
            super(looper);
            progressRequestListenerWeakReference = new WeakReference<>(listener);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_UPDATE:
                    ProgressListener uiProgressRequestListener = progressRequestListenerWeakReference.get();
                    if (uiProgressRequestListener != null) {
                        ProgressBean progressBean = (ProgressBean) msg.obj;
                        uiProgressRequestListener.onProgress(progressBean.getProgress(), progressBean.getTotal(), progressBean.isDone());
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    }

    private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);

    public void progress(long progress,long total,boolean done) {

        Message message = Message.obtain();
        message.obj = new ProgressBean(progress, total, done);
        message.what = REQUEST_UPDATE;
        mHandler.sendMessage(message);
    }

    public abstract void onProgress(long progress,long total,boolean done);
}
